import BaseElement from "../../core/BaseElement";
import TabBar, { Tab, TabConfig } from "../../core/TabBar";
import MainPageBox from "./MainPageBox";
import GlobalTabBar from "./GlobalTabBar";
import Login from "../../pages/Login";
import {readFileSync} from 'fs';
import Program from "../../../ConnectPool";
import PopUp, { PopUpConfig } from "../../core/PopUp";
import RightMenu from "../RightMenu";
import Modal, { ModalConfig } from "../Modal";
import { RightMenuListItem } from "../RightMenuListItem";
import AppManagerApp from "../../../apps/AppManager/AppManagerApp";
import FileManagerApp from "../../../apps/FileManager/FileManagerApp";
import { ipcRenderer } from "electron";
import ControlPanel from "./ControlPanel";
import { MsgType } from "../../../IVsshStatus";
import Tools from "../../../Tools";
import CONNECT_POOL from "../../../ConnectPool";
import Status from "../../../StatusManager";
import BottomBar from "./BottomBar";

/**
 * 整个程序的界面v2.1-20210121
 * v2.2-20210204 添加关闭弹窗的方法
 */
export default class Container extends BaseElement{
    ctrl:ControlPanel;
    tabBar:GlobalTabBar;
    rightMenu:PopUp<Array<RightMenuListItem>>;
    modal:PopUp<ModalConfig>;
    modalBody=new Modal();
    userDataPath="";
    constructor(){
        super();
        this.setId("vssh-container")
        this.tabBar= new GlobalTabBar({pageBox:new MainPageBox({
            container:this
        })});
        this.rightMenu=new PopUp<Array<RightMenuListItem>>(
            new RightMenu()
        );
        this.modal=new PopUp<ModalConfig>(
            this.modalBody
        );
        this.ctrl=new ControlPanel();
        this.modalBody.addEventListener("ok",this.modal.close);
        this.modalBody.addEventListener("cancel",this.modal.close);
    }
    addEventListener(type: keyof HTMLElementEventMap, listener: (e: Event) => void): void {
        throw new Error("Method not implemented.");
    }

    addMessage(title:string,info:string,type:MsgType){
        return this.ctrl.addMessage(title,info,type);
    }

    /**
     * 新建标签页
     * @param props 标签页设置
     * @returns 标签索引
     */
    addNewTab(props:TabConfig){
        return this.tabBar.addTab(new Tab(props));
    }

    /**
     * 添加一个已经实例化的标签页
     * @param tab 
     * @returns 标签索引
     */
    addTab(tab:Tab){
        return this.tabBar.addTab(tab);
    }

    /**
     * 关闭弹窗
     */
    closeModal(){
        this.modal.hidden()
    }

    /**
     * 创建弹窗
     * @param config 
     */
    createModal(config:PopUpConfig<ModalConfig>){
        this.modal.open(config);
        if(config.data.onCancel){
            this.modalBody.addEventListener("cancel",config.data.onCancel);
        }
        if(config.data.onClose){
            this.modalBody.addEventListener("close",config.data.onClose);
        }
        if(config.data.onOk){
            this.modalBody.addEventListener("ok",config.data.onOk);
        }
    }

    /**
     * 创建右键菜单
     * @param config 
     */
    createRightMenu(config:PopUpConfig<Array<RightMenuListItem>>){
        if(config.data.length>0){
            this.rightMenu.open(config);
        }
    }

    /**
     * 根据索引获取标签
     * @param index 标签的索引
     * @returns 
     */
    getTab(index:number){
        return this.tabBar.getTab(index);
    }

    removeMessage(index:number){
        this.ctrl.removeMessage(index);
    }

    async updateData(){
        this.userDataPath=await ipcRenderer.invoke ("get-user-data-path")
    }
    beforeRender() {
        let frame=this.createChild();
        frame.style.display="flex";
        frame.style.height="calc(100% - 20px)";
        frame.setInnerElement(this.ctrl);
        frame.appendChild(this.tabBar);
        const btmBar=new BottomBar();
        this.appendChild(frame);
        this.appendChild(btmBar);
        this.appendChild(this.rightMenu);
        this.appendChild(this.modal)

        let RsaPath=localStorage.getItem("privateKeyPath");
        if(!RsaPath){
            RsaPath=`/home/${process.env['USER']}/.ssh/id_rsa`;//默认是linux
            if(process.platform=="darwin"){
                RsaPath=`/Users/${process.env['USER']}/.ssh/id_rsa`; //mac
            }else if(process.platform=="win32"){
                console.warn("路径",this.userDataPath)
                RsaPath=`${this.userDataPath}/.ssh/id_rsa`; //windows
            }
        }
        let login =new Login({
            host:<string>localStorage.getItem("host"),
            port:<string>localStorage.getItem("port"),
            username:<string>localStorage.getItem("username"),
            password:<string>localStorage.getItem("password"),
            privateKeyPath:RsaPath
        })
        // buttonLogin.innerText=`使用${process.platform}登录，位于${process.env['USER']},${localStorage.getItem("host")}`;
        
        // 初始化标签
        let pageId=this.addNewTab({
            name:"登录",
            page:login
        });
        
        let defaultTab=this.getTab(pageId);
        if(!defaultTab){
            throw new Error("无法获取标签");
        }
        
        defaultTab.activated()
    
        login.addEventListener('login',async ()=>{
            console.log(login.getPassword());
            let password=login.getPassword();
            let username=login.getUsername();
            localStorage.setItem("host", login.getHost());
            localStorage.setItem("port", login.getPort());
            localStorage.setItem("username", login.getUsername());
            localStorage.setItem("password", login.getPassword());
            localStorage.setItem("privateKeyPath",login.getPrivateKeyPath())

            Status.setHost(login.getHost());
            Status.setPort(parseInt(login.getPort()));
            Status.setUsername(login.getUsername());
            Status.setPassword(login.getPassword());
    
            let privateKey:Buffer|undefined
            try{
                privateKey=readFileSync(login.getPrivateKeyPath())
                Status.setPrivateKey(privateKey);
            }catch(e){
                alert("无法读取私钥！")
                login.closeLoadding();
            }
            
            if(privateKey){

                let connected=false;
                try{
                    connected=await CONNECT_POOL.connectTest();
                }catch(e){
                    console.error(e);
                    alert("登录参数错误，请检查用户名密码主机端口是否正确");
                    login.closeLoadding();
                }

                // await Tools.sleep(1000000);
    
                if(connected){
                    let am=new AppManagerApp();
                    am.onStart();
                    let fm=new FileManagerApp();
                    console.error(defaultTab,pageId)
                    fm.onStart({
                        tab:defaultTab
                    });
                }
                
            }
        });
    }
}
export interface containerInject{
    tabBar:GlobalTabBar
}